package com.zjw.zy.heart.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.NonNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;

public final class JsonUtils {

    private static final String TAG = "JsonUtils";
    private static final ObjectMapper mapper = new ObjectMapper();

    public static String toJson(Object object) {
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            LogUtils.e(TAG, e.getMessage(), e);
            return "";
        }
    }


    public static <T> T fromJson(@NonNull String json, @NonNull Class<T> clazz) {
        try {
            return mapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            LogUtils.e(TAG, e.getMessage(), e);
            return null;
        }
    }

    public static <T> T fromJson(@NonNull String json, @NonNull TypeReference<T> type) {
        try {
            return mapper.readValue(json, type);
        } catch (JsonProcessingException e) {
            LogUtils.e(TAG, e.getMessage(), e);
            return null;
        }
    }

    public static String getNode(@NonNull String json, @NonNull String node) {
        try {
            JSONObject jsonObject = new JSONObject(json);

            return jsonObject.getString(node);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "";
    }

}
